const express = require('express');
const router = express.Router();
const { body } = require('express-validator');
const contactController = require('../controllers/contactController');
const { authenticate, isAdmin } = require('../middlewares/authMiddleware');
const { validate } = require('../middlewares/validationMiddleware');

// 搜索联系人
router.get('/search', authenticate, contactController.searchContacts);

// 获取最近联系人
router.get('/recent', authenticate, contactController.getRecentContacts);

// 获取所有联系人
router.get('/', authenticate, contactController.getContacts);

// 获取单个联系人详情
router.get('/:id', authenticate, contactController.getContact);

// 更新联系人CRM信息
router.patch(
  '/:id/crm',
  [
    authenticate,
    body('product').optional(),
    body('quantity').optional(),
    body('location').optional(),
    body('notes').optional(),
    body('status').optional().isIn(['lead', 'prospect', 'customer', 'inactive'])
      .withMessage('状态必须是lead/prospect/customer/inactive中的一个'),
    body('industry').optional(),
    body('source').optional(),
    validate
  ],
  contactController.updateCrmInfo
);

// 获取所有CRM客户
router.get('/crm/customers', authenticate, contactController.getAllCrmCustomers);

// 添加CRM客户
router.post('/crm/customers', authenticate, contactController.addCrmCustomer);

// 更新CRM客户信息
router.put('/crm/customers/:id', authenticate, contactController.updateCrmInfo);

// 更新CRM客户状态
router.patch(
  '/crm/customers/:id/status',
  [
    authenticate,
    body('status').isIn(['lead', 'prospect', 'customer', 'inactive'])
      .withMessage('状态必须是lead/prospect/customer/inactive中的一个'),
    validate
  ],
  contactController.updateCrmStatus
);

// 删除CRM客户
router.delete('/crm/customers/:id', authenticate, contactController.deleteCrmCustomer);

// 批量删除CRM客户
router.delete('/crm/customers/batch', authenticate, contactController.batchDeleteCustomers);

// 更新客户评分
router.put(
  '/crm/customers/:id/rating',
  [
    authenticate,
    body('rating').isInt({ min: 0, max: 5 }).withMessage('评分必须是0到5之间的整数'),
    validate
  ],
  contactController.updateCustomerRating
);

// 导出CRM数据
router.get('/crm/export', authenticate, contactController.exportCrmData);

// 获取CRM统计数据
router.get('/crm/stats', authenticate, contactController.getCrmStats);

module.exports = router; 